package com.piggy.logi.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.piggy.common.core.constant.SecurityConstants;
import com.piggy.common.core.utils.PageUtils;
import com.piggy.common.core.utils.sql.SqlUtil;
import com.piggy.common.core.web.page.PagePlus;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.logi.sys.bo.LogiCustomerQueryBo;
import com.piggy.logi.sys.bo.LogiGoodSourceEditBo;
import com.piggy.logi.sys.bo.LogiGoodSourceQueryBo;
import com.piggy.logi.sys.domain.LogiGoodSource;
import com.piggy.logi.sys.mapper.LogiGoodSourceMapper;
import com.piggy.logi.sys.service.ILogiCustomerService;
import com.piggy.logi.sys.service.ILogiGoodSourceService;
import com.piggy.logi.sys.vo.LogiCustomerExtVo;
import com.piggy.logi.sys.vo.LogiGoodSourceExtVo;
import com.piggy.sys.api.RemoteDistrictService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class LogiGoodSourceServiceImpl extends ServiceImpl<LogiGoodSourceMapper, LogiGoodSource> implements ILogiGoodSourceService {

    @Resource
    private ILogiCustomerService logiCustomerService;
    @Resource
    private RemoteDistrictService remoteDistrictService;

    @Override
    public LogiGoodSourceExtVo queryById(Long id) {
        LogiGoodSourceExtVo sourceExtVo = getVoById(id, LogiGoodSourceExtVo.class);
        if (sourceExtVo == null) {
            return null;
        }
        // 获取地址数据
        List<String> districtIds = Lists.newArrayList(ObjectUtil.defaultIfNull(sourceExtVo.getProduceDistrictId(),0).toString());
        Map<String, String> districtMap = remoteDistrictService.getDistrictMap(districtIds, SecurityConstants.INNER).getData();
        sourceExtVo.setProduceDistrictName(districtMap.get(ObjectUtil.defaultIfNull(sourceExtVo.getProduceDistrictId(),0).toString()));

        // 获取货主信息
        LogiCustomerQueryBo queryBo = new LogiCustomerQueryBo();
        queryBo.setCustomerIdList(Lists.newArrayList(sourceExtVo.getGoodsOwnerId()));
        List<LogiCustomerExtVo> customerExtVoList = logiCustomerService.queryList(queryBo);
        Map<Long, LogiCustomerExtVo> customerExtVoMap = customerExtVoList.stream().collect(Collectors.toMap(LogiCustomerExtVo::getCustomerId, Function.identity()));
        sourceExtVo.setCustomerExtVo(customerExtVoMap.get(sourceExtVo.getGoodsOwnerId()));
        return sourceExtVo;
    }

    @Override
    public TableDataInfo<LogiGoodSourceExtVo> queryPageList(LogiGoodSourceQueryBo bo) {
        PagePlus<LogiGoodSource, LogiGoodSourceExtVo> result = pageVo(PageUtils.buildPagePlus(bo, true), buildQueryWrapper(bo), LogiGoodSourceExtVo.class);
        List<LogiGoodSourceExtVo> goodSourceExtVos = result.getRecordsVo();
        fillData(goodSourceExtVos);
        return PageUtils.buildDataInfo(result);
    }

    private void fillData(List<LogiGoodSourceExtVo> goodSourceExtVos) {
        // 获取地址数据
        List<String> districtIds = goodSourceExtVos.stream().map(item -> ObjectUtil.defaultIfNull(item.getProduceDistrictId(),0).toString()).collect(Collectors.toList());
        Map<String, String> districtMap = remoteDistrictService.getDistrictMap(districtIds, SecurityConstants.INNER).getData();

        // 获取货主信息
        List<Long> customerIds = goodSourceExtVos.stream().map(LogiGoodSourceExtVo::getGoodsOwnerId).distinct().collect(Collectors.toList());
        LogiCustomerQueryBo queryBo = new LogiCustomerQueryBo();
        queryBo.setCustomerIdList(customerIds);
        List<LogiCustomerExtVo> customerExtVoList = logiCustomerService.queryList(queryBo);
        Map<Long, LogiCustomerExtVo> customerExtVoMap = customerExtVoList.stream().collect(Collectors.toMap(LogiCustomerExtVo::getCustomerId, Function.identity()));

        goodSourceExtVos.forEach(goodSourceExtVo -> {
            goodSourceExtVo.setCustomerExtVo(customerExtVoMap.get(goodSourceExtVo.getGoodsOwnerId()));

            goodSourceExtVo.setProduceDistrictName(districtMap.get(ObjectUtil.defaultIfNull(goodSourceExtVo.getProduceDistrictId(),0).toString()));
        });
    }

    @Override
    public List<LogiGoodSourceExtVo> queryList(LogiGoodSourceQueryBo bo) {
        List<LogiGoodSourceExtVo> goodSourceExtVos = listVo(buildQueryWrapper(bo), LogiGoodSourceExtVo.class);
        fillData(goodSourceExtVos);
        return goodSourceExtVos;
    }

    private LambdaQueryWrapper<LogiGoodSource> buildQueryWrapper(LogiGoodSourceQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<LogiGoodSource> lqw = Wrappers.lambdaQuery();
        //lqw.eq(LogiGoodSource::getDeptId, bo.getDeptId());
        lqw.like(StrUtil.isNotBlank(bo.getGoodsName()), LogiGoodSource::getGoodsName, bo.getGoodsName());
        lqw.eq(bo.getGoodsType() != null, LogiGoodSource::getGoodsType, bo.getGoodsType());
        //lqw.eq(bo.getDeptId() != null, LogiGoodSource::getDeptId, bo.getDeptId());
        lqw.like(StrUtil.isNotBlank(bo.getGoodCode()), LogiGoodSource::getGoodCode, bo.getGoodCode());
        if (CollUtil.isNotEmpty(bo.getCreateTimeStr())) {
            lqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') >= {0}", bo.getCreateTimeStr().get(0));
            lqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') <= {0}", bo.getCreateTimeStr().get(1));
        }

        lqw.in(CollUtil.isNotEmpty(bo.getGoodIds()), LogiGoodSource::getGoodId, bo.getGoodIds());
        // 部门数据权限过滤
        if (ObjectUtil.isNotNull(bo.getDeptId())) {
            SqlUtil.dataPermissionFilter(lqw, bo.getDeptId());
        }
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(LogiGoodSourceEditBo bo) {
        LogiGoodSource add = BeanUtil.toBean(bo, LogiGoodSource.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(LogiGoodSourceEditBo bo) {
        LogiGoodSource update = BeanUtil.toBean(bo, LogiGoodSource.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(LogiGoodSource entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    public List<LogiGoodSource> queryListByOrderIds(List<Long> goodOrderIds) {
        if (CollUtil.isEmpty(goodOrderIds)) {
            return Lists.newArrayList();
        }
        return baseMapper.queryListByOrderIds(goodOrderIds);
    }
}
